package com.bailan.foreat.es;

import com.bailan.foreat.entity.Product;
import com.bailan.foreat.entity.Store;
import com.bailan.foreat.mapper.ProductMapper;
import com.bailan.foreat.mapper.ProtypeMapper;
import com.bailan.foreat.mapper.StoreMapper;
import com.bailan.foreat.vo.EsProduct;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component("esProduct")
public class ESProductDataWriter implements ESDataWriter{

    @Autowired
    ESProductRepository esProductRepository;

    @Autowired
    ProductMapper productMapper;

    @Autowired
    ProtypeMapper protypeMapper;

    @Autowired
    StoreMapper storeMapper;

    public void dataWrite() {
        //将mysql中的数据全部读取出来,然后写入到es中
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        List<Product> productList = productMapper.selectAllProducts();

        List<EsProduct> esProductList = productList.stream().map(product -> {
            EsProduct esProduct = new EsProduct();

            List<Integer> allTypeIds = protypeMapper.getAllTypeIds(product.getId());
            List<String> typeNames = protypeMapper.getAllTypeNames(product.getId());
            Store store = storeMapper.selectById(product.getStoreId());
            System.out.println(product);
            esProduct.setStoreName(store.getStoreName());
            esProduct.setTypeName(typeNames);
            esProduct.setTypeIds(allTypeIds);
            esProduct.setId(product.getId());
            esProduct.setProductName(product.getProductName());
            esProduct.setProductPrice(product.getProductPrice());
            esProduct.setProductImg(product.getProductImg());
            esProduct.setStockCount(product.getStockCount());
            esProduct.setBuyCount(product.getBuyCount());
            esProduct.setType(product.getType());
            esProduct.setStoreId(product.getStoreId());
            esProduct.setStatus(product.getStatus());

            return esProduct;
        }).collect(Collectors.toList());
        esProductRepository.saveAll(esProductList);

    }

}
